// 周 文字
const WEEK_TEXT = ['日', '一', '二', '三', '四', '五', '六']

/**
 * @description: 获取day列表
 * @param config 配置
 * @return str[]
 */
function getDayList(config) {
	// dayList初始化
	const dayList = [];
	const setUp = +config.setUp[0] + config.setUp[1] / 60;
	const closing = +config.closing[0] + config.closing[1] / 60;
	const startTime = +config.hour + config.min / 60;
	let localMonth = config.month;
	let hourNum = config.maxRange + parseInt(config.hour);
	let dayNum = Math.ceil(hourNum / 24);
	hourNum = hourNum % 24;


	// 整天+1天
	if (hourNum == 0) {
		dayNum++;
		config.lastDayMaxTime = [(config.hour > 9 ? config.hour : `0${config.hour}`), config.min]
	}
	// 小于营业时间
	else if (hourNum < setUp) {
		if (closing - startTime >= config.minRange) {
			dayNum--; // +1天
			config.lastDayMaxTime = config.closing;
		} else {
			config.lastDayMaxTime = config.setUp;
		}
	}
	// 大于营业结束时间，以当天营业结束最大
	else if (hourNum > closing) {
		// 结束时间-当前时间 大等于 最小范围
		if (closing - startTime >= config.minRange) {
			config.lastDayMaxTime = config.closing;
		} else {
			dayNum++; // +1天
			config.lastDayMaxTime = config.setUp;
		}
	}
	// 在营业范围内
	else {
		const hourIntgerNum = parseInt(hourNum);
		config.lastDayMaxTime = [(hourIntgerNum > 9 ? `${hourIntgerNum}` : `0${hourIntgerNum}`), config.min]
	}

	while (dayNum > 0) {
		let localYear = config.year;
		if (localMonth == 13) {
			localYear += 1;
		}
		if (localMonth >= 13) {
			localMonth -= 12;
		}
		// 当月最后一天
		const tempDate = new Date(localYear, localMonth, 0)
		// 当月天数
		const curMonthDays = tempDate.getDate();
		// 最后一天星期几
		const dayIndex = tempDate.getDay();

		// 本月
		if (localMonth == config.month) {
			for (let j = config.day; j <= curMonthDays && dayNum > 0; j++) {
				let m = localMonth;
				let d = j;
				// 星期下标
				let dIndex = dayIndex + ((j - curMonthDays) % 7);
				if (dIndex < 0) {
					dIndex += 7
				}

				if (localMonth < 10) {
					m = '0' + parseInt(m);
				}
				if (j < 10) {
					d = '0' + parseInt(d);
				}
				let str = m + '月' + d + '日';
				let localeStr = localYear + '/' + m + '/' + d

				if (localeStr == new Date().toLocaleDateString()) {
					str += '今天'
				} else {
					str += '周' + WEEK_TEXT[dIndex]
				}
				dayList.push(str);
				// dayNum减去添加到dayList的个数
				dayNum--;
			}
		}
		// 非本月
		else {
			for (let j = 1; j <= curMonthDays && dayNum > 0; j++) {
				let m = localMonth;
				let d = j;
				// 星期下标
				let dIndex = dayIndex + ((j - tempDate.getDate()) % 7);
				if (dIndex < 0) {
					dIndex += 7
				}

				if (localMonth < 10) {
					m = '0' + parseInt(m);
				}
				if (j < 10) {
					d = '0' + parseInt(d);
				}
				let str = m + '月' + d + '日';

				str += '周' + WEEK_TEXT[dIndex]
				dayList.push(str);
				// dayNum减去添加到dayList的个数
				dayNum--;
			}
		}
		// 总天数不够，月份+1
		localMonth++;
	}
	return dayList;
}

/**
 * @description: 获取 时间取整  00:23 00:30
 * @return str[]
 */
function getIntegerTime(timeStr) {
	if (Array.isArray(timeStr)) {
		return timeStr
	}
	let [hour, min] = timeStr.split(':');

	// 23小时，不是00分都按30分
	if (hour === '23') {
		if (min !== '00') {
			min = '30'
		}
	} else {
		// 0>min>=30
		if (min > 0) {
			min = '30';
		}
		// 30>min>Infinity
		else if (min > 30) {
			min = '00';
			hour++;
		}
		//  00分 不修改
	}

	return [
		hour,
		min
	]
}

/**
 * @description: 获取hour列表，根据门店开始结束时间生成
 * @return str[]
 */
function getHourList(config, dayTotal) {
	// hourList初始化
	const hourList = [];
	const firstDayHourList = [];
	const lastDayHourList = [];
	const [setUpHour, setUpMin] = config.setUp;
	const [closingHour, closingMin] = config.closing;
	let maxHour = -1;
	if (config.lastDayMaxTime) {
		maxHour = +config.lastDayMaxTime[0]
	}

	for (let hour = +setUpHour; hour < +closingHour + 1; hour++) {
		let hourStr = hour >= 10 ? (hour + '') : ('0' + hour)
		hourList.push(hourStr)
		if (hour >= config.hour) {
			if (dayTotal === 1) {
				if (hour <= maxHour) {
					firstDayHourList.push(hourStr)
				}
			} else {
				firstDayHourList.push(hourStr)
			}
		}

		if (hour <= maxHour) {
			lastDayHourList.push(hourStr)
		}
	}

	return {
		hourList,
		firstDayHourList,
		lastDayHourList
	};
}
/**
 * @description: 获取min列表
 * @return str[]
 */
function getMinList(config) {
	const minList = ['00', '30']
	const firstHourMinList = config.setUp[1] == '30' ? ['30'] : minList;
	const lastHourMinList = config.closing[1] == '00' ? ['00'] : minList;
	const firstDayHourMinList = config.min == '30' ? ['30'] : minList;
	const lastDayHourMinList = config.min == '00' ? ['00'] : minList;
	return {
		minList,
		firstHourMinList,
		lastHourMinList,
		firstDayHourMinList,
		lastDayHourMinList
	}
}

// 获取推迟valueArr
function getDeferValueArr(config, hourLists, deferHour) {
	if (deferHour > config.maxRange) {
		return [999, 999, 999]
	}
	const valueArr = [0, 0, 0];

	const closing = +config.closing[0] + config.closing[1] / 60;
	const setUp = +config.setUp[0] + config.setUp[1] / 60;
	let hourNum = deferHour + parseInt(config.hour);
	valueArr[0] = Math.floor(hourNum / 24);
	hourNum = hourNum % 24;

	if (config.min == '30') {
		valueArr[2] = 1
	}

	// 不够推到营业开始时间
	if (hourNum <= setUp) {
		valueArr[1] = 0;
	} else {
		// 大于营业结束时间
		if (hourNum > closing) {
			valueArr[0]++;
		}
		// 小于营业结束
		else {
			const hourIntgerNum = parseInt(hourNum);
			if (valueArr[0] == 0) {
				valueArr[1] = hourLists.firstDayHourList.findIndex(item => item == hourIntgerNum)
			} else {
				valueArr[1] = hourLists.hourList.findIndex(item => item == hourIntgerNum)
			}
		}
	}

	return valueArr
}

// 初始化value
function initValue(config, hourLists) {
	// 开始时间的初始值
	let valueArr = [0, 0, 0];
	let minValueArr = [0, 0, 0];
	if (config.defer) {
		// 推迟时间（3天）超出自动定位到最大值
		valueArr = getDeferValueArr(config, hourLists, config.defer);
		minValueArr = getDeferValueArr(config, hourLists, config.minRange);
	}
	return {
		valueArr,
		minValueArr
	}
}

// 初始化config
function initConfig(config) {
	// 数据校验- maxRange 最小为2
	if (config.maxRange < 2) {
		config.maxRange = 2;
	}
	// 数据校验- 最小范围大于最小范围 取最大范围-1
	if (config.minRange > config.maxRange) {
		config.minRange = config.maxRange;
	}
	// 营业时间 取整0点或30分钟 转换为数组['00','30'] 最小00:00 最大23:30 
	config.setUp = getIntegerTime(config.setUp);
	config.closing = getIntegerTime(config.closing);
	if (config.setUp.toString() === config.closing.toString()) {
		console.warn('s-datetime-picker Error: 营业开始时间等于营业结束时间')
	}
	// 取出开始时间 年月日时分
	config.year = config.startTime.slice(0, 4);
	config.month = config.startTime.slice(5, 7);
	config.day = config.startTime.slice(8, 10);
	config.hour = config.startTime.slice(11, 13);
	config.min = config.startTime.slice(-2);
	// 计算营业时间
	config.businessHours = +config.closing[0] + (config.closing[1] / 60) - config.setUp[0] - (config.setUp[1] / 60);
}

/**
 * @description: 初始化picker的数据
 * @param config.startTime 	开始时间
 * @param config.setUp 		开业当天时间（小时）
 * @param config.close 		停业当天时间（小时）
 * @param config.maxRange 	最大范围（小时）
 * @param config.maxRange 	最大范围（小时）
 * @param config.defer 		推迟（小时）
 */
export function initPickerData(config) {
	// 初始化config
	initConfig(config);
	const dayList = getDayList(config);
	const hourLists = getHourList(config, dayList.length);
	const minLists = getMinList(config);
	const valueArrs = initValue(config, hourLists);
	return {
		dayList,
		...hourLists,
		...minLists,
		...valueArrs
	}
}
